package com.ewzj.bigdata.mvp.ui.activity

import android.animation.IntEvaluator
import android.animation.ValueAnimator
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.webkit.ConsoleMessage
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.widget.RelativeLayout
import com.ewzj.bigdata.R
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.extensions.dpToPx
import com.ewzj.bigdata.app.extensions.initwebview
import com.ewzj.bigdata.app.extensions.loadMiwoUrl
import com.ewzj.bigdata.app.utils.Apputils
import com.ewzj.bigdata.di.component.DaggerNewsWebActivityComponent
import com.ewzj.bigdata.di.module.NewsWebActivityModule
import com.ewzj.bigdata.mvp.contract.NewsWebActivityContract
import com.ewzj.bigdata.mvp.model.rspbean.InfoBean
import com.ewzj.bigdata.mvp.presenter.NewsWebActivityPresenter
import com.ewzj.bigdata.mvp.ui.view.ObservableScrollViewCallbacks
import com.ewzj.bigdata.mvp.ui.view.ScrollState
import com.ewzj.bigdata.mvp.ui.view.pathanimlib.PathAnimView
import com.jakewharton.rxbinding2.view.RxView
import com.jess.arms.base.BaseActivity
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.DeviceUtils
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import kotlinx.android.synthetic.main.activity_news_web.*
import kotlinx.android.synthetic.main.item_webview_comment.*
import kotlinx.android.synthetic.main.path_loading.*


class NewsWebActivity : BaseActivity<NewsWebActivityPresenter>(), NewsWebActivityContract.View {
    lateinit var infodata: InfoBean
    lateinit var tmpdata: InfoBean
    val shareWindow by lazy { Apputils.Utils.getShareWindow(llcoment) }
    var infolist=ArrayList<InfoBean>();
    override fun reloadurl(infobean: InfoBean) {
        infolist.add(infodata)
        if(!infobean.go_url.contains("zhuanti")){
            infobean.topic_sign="0"
            showComment()
        }else{
            infobean.topic_sign="1"
            hideComment()
        }
        infodata = infobean
        newwebview.loadMiwoUrl(infobean.go_url)
    }

    override fun showComment() {
        llcoment.visibility=View.VISIBLE
        showSerachBar(llcoment, 0, 54.dpToPx(this))
        newwebview.setScrollViewCallbacks(object : ObservableScrollViewCallbacks {
            override fun onScrollChanged(scrollY: Int, firstScroll: Boolean, dragging: Boolean) {

            }

            override fun onDownMotionEvent() {

            }

            override fun onUpOrCancelMotionEvent(scrollState: ScrollState?) {
                when (scrollState) {
                    ScrollState.DOWN -> {
                        show()
                    }
                    ScrollState.UP -> {
                        dismis()
                    }
                }
            }

        })
    }

    override fun resetHint(hint: String) {
        et_comment.setText("")
        et_comment.hint = hint
    }

    override fun resetTitle(title: String) {
        tv_title.text = title
    }

    override fun isColoected(iscoloected: Int) {
        iv_star.isSelected = iscoloected == 1
    }

    override fun initData(savedInstanceState: Bundle?) {
        infodata = intent.getParcelableExtra<InfoBean>(AppKey.EXTRA_DATA)
        tmpdata=infodata
        infolist.add(infodata)
        if (infodata == null) finish()
        newwebview.initwebview(rl_pathloading)
        (newwebview as WebView).setWebChromeClient(object :WebChromeClient(){
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress == 100) {
                    newwebview.settings.setBlockNetworkImage(false)
                    rl_pathloading.setVisibility(View.GONE)
                    (rl_pathloading.findViewById(R.id.pathAnimView1) as PathAnimView).stopAnim()
                    if (newwebview.canGoBack()){

                    }else{
                        if ("1".equals(tmpdata.topic_sign)){
                            resetTitle(tmpdata.title)
                            hideComment()
                        }else{
//                            resetTitle(tmpdata.title)
                        }

                    }
                }
                super.onProgressChanged(view, newProgress)
            }
        })
        initListener()
        mPresenter.initBridgeWebview(newwebview, infodata.go_url)
        Apputils.Utils.setPathandStart(rl_pathloading)
        if ("1".equals(infodata.topic_sign)){
            hideComment()
        }
    }

    private fun initListener() {
        isColoected(infodata.is_collect)
        if (infodata.getIs_self() === 0) {
            resetTitle("来源•" + infodata.getSources())
        } else {
            resetTitle(infodata.title)
        }
        RxView.clicks(tv_send).subscribe({
            if(Apputils.Utils.checkIsLogin(this)){
                mPresenter.doComment(et_comment.text.toString(), infodata)
                DeviceUtils.hideSoftKeyboard(this, tv_send)
            }else{
                LoginActivity.startLoginActivity(this)
            }

        })
        RxView.clicks(tv_share).subscribe({
            shareWindow.showAtLocation(llcoment, Gravity.BOTTOM, 0, 0)
            Apputils.Utils.setbackgroudAlpa(this, 0.6.toFloat())
        })
        RxView.clicks(shareWindow.contentView.findViewById(R.id.ll_qq)).subscribe({
            if ("0".equals(tmpdata.topic_sign)){
                mPresenter.ShareWeb(infodata, SHARE_MEDIA.QQ)
                shareWindow.dismiss()
            }else if ("1".equals(tmpdata.topic_sign)){
                if (newwebview.canGoBack()){
                    mPresenter.ShareWeb(infodata, SHARE_MEDIA.QQ)
                    shareWindow.dismiss()
                }else{
                    mPresenter.ShareWeb(tmpdata, SHARE_MEDIA.QQ)
                    shareWindow.dismiss()
                }
            }else{
                mPresenter.ShareWeb(infodata, SHARE_MEDIA.QQ)
                shareWindow.dismiss()
            }

        })
        RxView.clicks(shareWindow.contentView.findViewById(R.id.ll_qqzone)).subscribe({
            if ("0".equals(tmpdata.topic_sign)){
                mPresenter.ShareWeb(infodata, SHARE_MEDIA.QZONE)
                shareWindow.dismiss()
            }else if ("1".equals(tmpdata.topic_sign)){
                if (newwebview.canGoBack()){
                    mPresenter.ShareWeb(infodata, SHARE_MEDIA.QZONE)
                    shareWindow.dismiss()
                }else{
                    mPresenter.ShareWeb(tmpdata, SHARE_MEDIA.QZONE)
                    shareWindow.dismiss()
                }
            }else{
                mPresenter.ShareWeb(infodata, SHARE_MEDIA.QZONE)
                shareWindow.dismiss()
            }
        })
        RxView.clicks(shareWindow.contentView.findViewById(R.id.tv_cancel)).subscribe({
            shareWindow.dismiss()
        })
        RxView.clicks(shareWindow.contentView.findViewById(R.id.ll_wechat)).subscribe({
            if ("0".equals(tmpdata.topic_sign)){
                mPresenter.ShareWeb(infodata, SHARE_MEDIA.WEIXIN)
                shareWindow.dismiss()
            }else if ("1".equals(tmpdata.topic_sign)){
                if (newwebview.canGoBack()){
                    mPresenter.ShareWeb(infodata, SHARE_MEDIA.WEIXIN)
                    shareWindow.dismiss()
                }else{
                    mPresenter.ShareWeb(tmpdata, SHARE_MEDIA.WEIXIN)
                    shareWindow.dismiss()
                }
            }else{
                mPresenter.ShareWeb(infodata, SHARE_MEDIA.WEIXIN)
                shareWindow.dismiss()
            }
        })
        RxView.clicks(shareWindow.contentView.findViewById(R.id.ll_wechatzone)).subscribe({
            if ("0".equals(tmpdata.topic_sign)){
                mPresenter.ShareWeb(infodata, SHARE_MEDIA.WEIXIN_CIRCLE)
                shareWindow.dismiss()
            }else if ("1".equals(tmpdata.topic_sign)){
                if (newwebview.canGoBack()){
                    mPresenter.ShareWeb(infodata, SHARE_MEDIA.WEIXIN_CIRCLE)
                    shareWindow.dismiss()
                }else{
                    mPresenter.ShareWeb(tmpdata, SHARE_MEDIA.WEIXIN_CIRCLE)
                    shareWindow.dismiss()
                }
            }else{
                mPresenter.ShareWeb(infodata, SHARE_MEDIA.WEIXIN_CIRCLE)
                shareWindow.dismiss()
            }
        })
        RxView.clicks(shareWindow.contentView.findViewById(R.id.ll_sina)).subscribe({
            if ("0".equals(tmpdata.topic_sign)){
                mPresenter.ShareWeb(infodata, SHARE_MEDIA.SINA)
                shareWindow.dismiss()
            }else if ("1".equals(tmpdata.topic_sign)){
                if (newwebview.canGoBack()){
                    mPresenter.ShareWeb(infodata, SHARE_MEDIA.SINA)
                    shareWindow.dismiss()
                }else{
                    mPresenter.ShareWeb(tmpdata, SHARE_MEDIA.SINA)
                    shareWindow.dismiss()
                }
            }else{
                mPresenter.ShareWeb(infodata, SHARE_MEDIA.SINA)
                shareWindow.dismiss()
            }
        })
        RxView.clicks(iv_back).subscribe({
//            &&tmpdata.topic_sign.equals("1")
            if(newwebview.canGoBack()){
                var tmpinfo=infolist[infolist.lastIndex]
                resetTitle(tmpinfo.title)
                infodata=tmpinfo
                infolist.remove(tmpinfo)
                newwebview.goBack()
                if ("1".equals(infodata.topic_sign)){
                   hideComment()
                }else{
                  showComment()
                }
            }else{
                finish()
            }
           })
        RxView.clicks(iv_star).subscribe({
            if(Apputils.Utils.checkIsLogin(this)){
                iv_star.isSelected=!iv_star.isSelected
                mPresenter.doCollect(infodata)
            }else{
                LoginActivity.startLoginActivity(this)
            }
        })
        if ("0".equals(infodata.topic_sign)||infodata.topic_sign.isNullOrEmpty()){
            newwebview.setScrollViewCallbacks(object : ObservableScrollViewCallbacks {
                override fun onScrollChanged(scrollY: Int, firstScroll: Boolean, dragging: Boolean) {

                }

                override fun onDownMotionEvent() {

                }

                override fun onUpOrCancelMotionEvent(scrollState: ScrollState?) {
                    when (scrollState) {
                        ScrollState.DOWN -> {
                            show()
                        }
                        ScrollState.UP -> {
                            dismis()
                        }
                    }
                }

            })
        }

    }

    fun show() {
        if (llcoment.height == 0) {
            rl_partent.setPadding(0, 45.dpToPx(this), 0, 0)
            showSerachBar(llcoment, 0, 54.dpToPx(this))
            showSerachBar(ll_title, 0, 45.dpToPx(this))
        }
    }

    fun dismis() {
        if (llcoment.height != 0) {
            rl_partent.setPadding(0, 0, 0, 0)
            showSerachBar(llcoment, 54.dpToPx(this), 0)
            showSerachBar(ll_title, 45.dpToPx(this), 0)
        }
    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        DaggerNewsWebActivityComponent.builder().appComponent(appComponent)
                .newsWebActivityModule(NewsWebActivityModule(this))
                .build().inject(this)
    }

    override fun initView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_news_web
    }

    override fun showLoading() {

    }

    override fun launchActivity(intent: Intent?) {

    }

    override fun hideLoading() {

    }

    override fun killMyself() {

    }

    override fun showMessage(message: String?) {

    }

    companion object {
        fun startInfoActivity(context: Context, infobean: InfoBean) {
            val intent = Intent(context, NewsWebActivity::class.java)
            intent.putExtra(AppKey.EXTRA_DATA, infobean)
            context.startActivity(intent)
        }
    }

    fun showSerachBar(view: View, startValue: Int, endValue: Int) {
        //      RelativeLayout.LayoutParams layoutParams= (RelativeLayout.LayoutParams) rlSearch.getLayoutParams();
        val valueAnimator = ValueAnimator.ofInt(0, 100)
        valueAnimator.duration = 200
        valueAnimator.addUpdateListener { animation ->
            val animatorValue = animation.animatedValue as Int
            val fraction = animatorValue / 100f
            val mEvaluator = IntEvaluator()
            //3.使用IntEvaluator计算属性值并赋值给ListView的高
            val layoutParams = view.layoutParams as RelativeLayout.LayoutParams
            layoutParams.height = mEvaluator.evaluate(fraction, startValue, endValue)!!
            view.layoutParams = layoutParams
            view.requestLayout()
        }
        valueAnimator.setTarget(view)
        valueAnimator.start()
    }

    override fun onDestroy() {
        newwebview.removeAllViews()
        newwebview.destroy()
        super.onDestroy()

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    override fun useFragment(): Boolean {
        return false
    }

    override fun hideComment() {
        newwebview.setScrollViewCallbacks(null)
        llcoment.visibility=View.GONE
        val layoutParams = ll_title.layoutParams as RelativeLayout.LayoutParams
        layoutParams.height=45.dpToPx(this)
        ll_title.layoutParams=layoutParams
//        showSerachBar(ll_title, 45.dpToPx(this), 0)
        ll_title.visibility=View.VISIBLE
    }

}
